package com.lanyou.cook.upload.service.socket.upload;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

import com.lanyou.cook.upload.commons.Constants;
import com.lanyou.cook.upload.util.ExceptionToStrFactory;
import com.lanyou.cook.upload.util.PropFactory;

/**
 * 负责阻塞等待请求
 * @author ly-lihailang
 *
 */
public class ListenThread implements Runnable{
	private static Logger logger = Logger.getLogger(ListenThread.class); 
	private ServerSocket serverSocket;
	public ListenThread(){
	}
	/**
	 * @param serverSocket ServerSocket实例
	 * 根据ServerSocket实例创建线程，并启动
	 */
	public ListenThread(ServerSocket serverSocket){
		this.serverSocket =serverSocket;
		new Thread(this).start();
	}
	@Override
	public void run() {
		logger.info("[ListenThread.run]---------------------");
		//获取上传文件路径路径
		String filePath = PropFactory
				.getPropByKey(Constants.BUNDLE_FILE_UPLOAD_PATH);
		logger.info("[ListenThread.run]:上传路径"+filePath);
		File file = new File(filePath);
		if(!file.exists()){
			file.mkdir();
		}
		try{
			while (!serverSocket.isClosed()) {
				// 一旦有堵塞, 则表示服务器与客户端获得了连接
				Socket client = serverSocket.accept();
				// 处理这次连接
				new HandlerThread(client, filePath);
			}
		}catch(IOException e){
			logger.error("[ListenThread.run]:"+ExceptionToStrFactory.getErrorInfoFromException(e));
		}
		
	}

}
